package controllers

import (
	"ai/models"
	"ai/services"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

type LogController struct {
	logService services.LogService
}

func NewLogController(logService services.LogService) *LogController {
	return &LogController{logService: logService}
}

func (c *LogController) CreateLog(ctx *gin.Context) {
	// 从表单中获取参数
	aid := ctx.PostForm("aid")
	mid := ctx.PostForm("mid")
	param := ctx.PostForm("param")
	content := ctx.PostForm("content")
	channel := ctx.PostForm("channel")

	// 创建 ApiLog 对象
	log := models.ApiLog{
		Aid:        parseInt(aid), // 将字符串转换为 int
		Mid:        parseInt(mid), // 将字符串转换为 int
		Param:      param,
		Content:    content,
		Channel:    channel,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	// 调用Service层写入日志
	if err := c.logService.CreateLog(&log); err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(200, gin.H{"message": "Log created successfully"})
}

// 辅助函数：将字符串转换为 int
func parseInt(s string) int {
	var result int
	_, err := fmt.Sscanf(s, "%d", &result)
	if err != nil {
		return 0 // 如果转换失败，返回默认值 0
	}
	return result
}
